<template>
  <div class="app-container">
    <div class="search-container">
      <SltFromDepTree v-model="searchForm.departmentId" />
      <el-input
        v-model="searchForm.userName"
        prefix-icon="el-icon-search"
        clearable
        placeholder="请输入用户名"
        class="search-input"
        @keyup.enter.native="getList({ pageNo: 1 })"
      />
      <el-input
        v-model="searchForm.tel"
        prefix-icon="el-icon-search"
        clearable
        placeholder="请输入手机号"
        class="search-input"
        @keyup.enter.native="getList({ pageNo: 1 })"
      />
      <!--      <el-select v-model="searchForm.roleId" placeholder="请选择角色" clearable>-->
      <!--        <el-option-->
      <!--          v-for="item in chooseRoleList"-->
      <!--          :key="item.id"-->
      <!--          :label="item.name"-->
      <!--          :value="item.id"-->
      <!--        />-->
      <!--      </el-select>-->
      <el-button type="primary" icon="el-icon-search" size="small" @click="getList({ pageNo: 1 })">搜索</el-button>
    </div>
    <div class="function-buttons">
      <!--      <el-button v-hasPermission="['sys_user_add']" type="primary" size="small" icon="el-icon-edit" @click="save">新增</el-button>-->
    </div>
    <div>
      <el-table v-loading="listLoading" :data="list" border fit highlight-current-row>
        <el-table-column align="center" label="#" width="80" type="index" />
        <el-table-column align="center" label="用户名">
          <template slot-scope="scope">
            <span>{{ scope.row.userName }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="所属部门">
          <template slot-scope="scope">
            <span>{{ scope.row.departmentName }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="手机号">
          <template slot-scope="scope">
            <span>{{ scope.row.tel }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button v-hasPermission="['sys_user_addRole']" type="text" @click="role(scope.row.userId)">分配角色</el-button>
            <el-button
              v-hasPermission="['sys_user_data']"
              type="text"
              @click="orderRole(scope.row.userId)"
            >数据权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.pageNo"
        :limit.sync="listQuery.pageSize"
        @pagination="pageChange"
      />
    </div>
    <div>
      <el-dialog title="更新" :visible.sync="saveForm.visible" :close-on-click-modal="false">
        <el-form ref="saveForm" :model="saveForm.props" :rules="saveForm.rules" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="saveForm.props.username" />
          </el-form-item>
          <el-form-item label="昵 称" prop="name">
            <el-input v-model="saveForm.props.name" />
          </el-form-item>
          <el-form-item label="职位">
            <el-input v-model="saveForm.props.jobName" />
          </el-form-item>
          <el-form-item label="所属部门" prop="deptIdList">
            <el-cascader
              ref="cascader"
              v-model="saveForm.props.deptTreeList"
              :options="deptTreeList"
              :props="{ multiple: true, checkStrictly: true }"
              clearable
              style="width: 100%;"
            />
          </el-form-item>
          <el-form-item label="密 码" :prop="saveForm.props.id == '' ? 'password' : 'passwords'">
            <el-input v-model="saveForm.props.password" show-password />
          </el-form-item>
          <el-form-item label="电 话" prop="phone">
            <el-input v-model="saveForm.props.phone" />
          </el-form-item>
          <el-form-item label="邮 箱">
            <el-input v-model="saveForm.props.email" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel('saveForm')">取 消</el-button>
          <el-button type="primary" @click="doSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="工单数据权限" :visible.sync="orderAssignment.visible">
        <common-select v-model="orderAssignment.roleType" name="EnumOrderRoleType" placetext="请选择业务场景" />
        <el-form
          v-if="orderAssignment.roleType === '2'"
          ref="saveForm"
          label-width="80px"
          style="max-height: 500px;overflow: auto"
        >
          <el-tree
            ref="tree"
            :data="orderAssignment.dataList"
            show-checkbox
            :check-strictly="true"
            node-key="id"
            default-expand-all
            :props="orderAssignment.defaultProps"
            :default-checked-keys="orderAssignment.deptIds"
            @check="handleClick"
          />
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="orderAssignment.visible = false">取 消</el-button>
          <el-button type="primary" :disabled="btnSubmitDisabled" @click="assignmentDpetSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog title="角色" :visible.sync="roleForm.role">
        <el-checkbox-group v-model="checkList">
          <el-table :data="roles" border fit highlight-current-row>
            <el-table-column align="center" label="描 述">
              <template slot-scope="scope">
                <span>{{ scope.row.description }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="角色名">
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label=" " width="100px" type="index">
              <template slot-scope="scope">
                <el-checkbox :label="scope.row.id" class="role-checkbox" />
              </template>
            </el-table-column>
          </el-table>
        </el-checkbox-group>
        <div slot="footer" class="dialog-footer">
          <el-button @click="roleForm.role = false">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import request from '@/utils/request'
import encUtil from '@/utils/commonUtils'
import CommonSelect from '@/components/wejoy/CommonSelect.vue'
import SltFromDepTree from '@/components/SltFromDepTree/SltFromDepTree.vue'

export default {
  name: 'TopicList',
  // eslint-disable-next-line vue/no-unused-components
  components: { CommonSelect, Pagination, encUtil, SltFromDepTree },
  data() {
    const passwordRule = (rule, value, callback) => {
      if (!rule.required && !this.saveForm.props.password) {
        callback();
      }
      const regExp = /^(?![0-9]+$)(?![a-zA-Z]+$)(?![`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\$\^]+$)[0-9A-Za-z`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\$\^]{8,16}$/;
      if (!regExp.test(this.saveForm.props.password)) {
        callback(new Error('密码由数字、字母、特殊字符组成，且长度要在8-16位之间。'));
      } else {
        callback();
      }
    };
    return {
      chooseRoleList: [],
      checkList: [],
      delUser: false,
      uploadAction: this.cfg.apiDomain + '/file/upload/upload?uploadItem=topicPostImg',
      list: null,
      keywords: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      roles: null,
      currentRole: null,
      roleForm: {
        role: false,
        userId: '',
        props: {
          id: '',
          name: '',
          description: ''
        }
      },
      searchForm: {
        username: '',
        tag: ''
      },
      btnSubmitDisabled: false,
      orderAssignment: {
        visible: false,
        dataList: [],
        deptIds: [],
        userId: '',
        roleType: '',
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      deptTreeList: [],
      saveForm: {
        visible: false,
        props: {
          id: '',
          username: '',
          password: '',
          name: '',
          phone: '',
          operator: '',
          createTime: '',
          tag: '',
          deptTreeList: [],
          isSecondLanding: '',
          jobName: ''
        },
        rules: {
          username: this.formRules({
            required: true,
            min: 1,
            max: 100
          }),
          password: [{ required: true, trigger: 'blur', validator: passwordRule }],
          passwords: [{ required: false, trigger: 'blur', validator: passwordRule }],
          phone: this.formRules({
            required: true,
            min: 1,
            max: 20,
            type: 'phoneNumber'
          }),
          name: this.formRules({
            required: true,
            min: 1,
            max: 50
          }),
          email: this.formRules({
            required: true,
            min: 1,
            max: 100,
            type: 'email'
          }),
          postImgPath: this.formRules({
            required: true
          }),
          title: this.formRules({
            required: true,
            min: 1,
            max: 100
          }),
          announcement: this.formRules({
            required: true,
            min: 1,
            max: 200
          }),
          validDateRange: this.formRules({
            type: 'array',
            required: true
          }),
          contentPath: this.formRules({
            required: true
          })
        }
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.getRoleList();
    this.registerFilter('RoleSerachUser');
    this.getList({
      pageNo: this.listQuery.pageNo
    })
  },
  methods: {
    pageChange(page) {
      this.getList({
        pageNo: page.page
      })
    },
    getList() {
      this.listLoading = true
      request({
        url: '/system/evsUser/getPageList',
        method: 'post',
        data: {
          status: 0,
          pageNo: this.listQuery.pageNo,
          pageSize: this.listQuery.pageSize,
          ...this.searchForm
        }
      }).then(res => {
        const data = res.data
        this.list = data.rows
        this.total = data.total
        this.listLoading = false
      })
    },
    getRoleList() {
      const _this = this;
      request({
        url: '/system/sysRole/getPageList',
        method: 'post',
        data: {
          pageNo: 1,
          pageSize: 100
        }
      }).then(res => {
        const data = res.data
        _this.roles = data.rows
        _this.chooseRoleList = data.rows
      })
    },
    save() {
      this.saveForm.props = {
        id: '',
        username: '',
        name: '',
        password: '',
        phone: '',
        email: '',
        operator: '',
        createTime: '',
        tag: '',
        deptTreeList: [],
        tagList: [],
        isSecondLanding: '0',
        jobName: ''
      };
      this.saveForm.visible = true
    },
    update(data) {
      this.saveForm.props = {
        id: data.id,
        username: data.username,
        password: '',
        phone: data.phone,
        email: data.email,
        name: data.name,
        tag: data.tag,
        jobName: data.jobName,
        deptTreeList: data.deptTreeList,
        tagList: data.tagList == null ? [] : data.tagList,
        isSecondLanding: data.isSecondLanding.toString()
      };
      this.saveForm.visible = true
    },
    del(id) {
      request({
        url: '/system/sysUser/delete',
        method: 'post',
        params: {
          id: id
        }
      }).then(res => {
        this.$message.success('删除成功')
        this.getList({
          pageNo: 1
        });
        this.delUser = false;
      })
    },
    assignmentDpetSave() {
      const _this = this;
      this.btnSubmitDisabled = true;
      request({
        url: '/system/sysRoleOrder/addDeptRole',
        method: 'post',
        data: {
          dptIds: this.orderAssignment.resourcesIds,
          userId: this.orderAssignment.userId,
          roleType: this.orderAssignment.roleType
        }
      }).then(res => {
        _this.$message.success('保存成功');
        _this.orderAssignment.visible = false;
        _this.btnSubmitDisabled = false;
      }).catch(e => {
        _this.btnSubmitDisabled = false;
      })
    },
    doSave() {
      const _this = this;
      this.$refs.saveForm.validate(valid => {
        if (!valid) {
          return;
        }
        _this.saveForm.props.deptIdList = [];
        for (var i = 0; i < _this.saveForm.props.deptTreeList.length; i++) {
          var valElement = _this.saveForm.props.deptTreeList[i];
          _this.saveForm.props.deptIdList.push(valElement[valElement.length - 1]);
        }
        _this.saveForm.props.tag = _this.saveForm.props.tagList.toString();
        request({
          url: '/system/sysUser/save',
          method: 'post',
          data: {
            id: _this.saveForm.props.id,
            username: _this.saveForm.props.username,
            password: encUtil.encodeRSA(_this.saveForm.props.password, null),
            phone: _this.saveForm.props.phone,
            name: _this.saveForm.props.name,
            email: _this.saveForm.props.email,
            tag: _this.saveForm.props.tag,
            deptIdList: _this.saveForm.props.deptIdList,
            isSecondLanding: _this.saveForm.props.isSecondLanding,
            jobName: _this.saveForm.props.jobName
          }
        }).then(res => {
          _this.$message.success('保存成功');
          _this.getList({
            pageNo: 1
          });
          _this.saveForm.visible = false;
        })
      });
    },
    getCurrentRole(id) {
      const _this = this;
      request({
        url: 'system/sysUserRole/getPageList',
        method: 'post',
        data: {
          sysUserId: id,
          pageNo: 1,
          pageSize: 100
        }
      }).then(res => {
        const data = res.data.rows
        var roleIds = [];
        for (var i = 0; i < data.length; i++) {
          roleIds.push(data[i]['sysRoleId'])
        }
        _this.checkList = roleIds
      })
    },
    getOrderDeptRole(data) {
      const _this = this;
      request({
        url: '/system/sysDept/getDepTreeList',
        method: 'post',
        data: {}
      }).then(res => {
        _this.orderAssignment.dataList = res.data;
        if (data != null) {
          _this.$nextTick(function() {
            _this.$refs.tree.setCheckedKeys(data);
          })
        }
      })
    },
    getOrderDeptRoleIds(id) {
      const _this = this;
      request({
        url: '/system/sysRoleOrder/getDeptIdListByUserId/' + id,
        method: 'get'
      }).then(res => {
        this.orderAssignment.deptIds = res.data.ids
        this.orderAssignment.roleType = res.data.roleType + ''
        console.log(this.orderAssignment.roleType)
        _this.getOrderDeptRole(_this.orderAssignment.deptIds)
      })
    },
    handleClick(nodeObj, selectedObj) {
      this.orderAssignment.resourcesIds = selectedObj.checkedKeys.concat(selectedObj.halfCheckedKeys);
      console.log(this.orderAssignment.resourcesIds);
    },
    role(id) {
      this.checkList = [];
      this.getRoleList()
      this.getCurrentRole(id)
      this.roleForm.props = {
        id: '',
        name: '',
        description: ''
      };
      this.roleForm.role = true
      this.roleForm.userId = id
    },
    orderRole(id) {
      this.orderAssignment.visible = true
      this.orderAssignment.userId = id
      this.getOrderDeptRole();
      this.getOrderDeptRoleIds(id);
    },
    addRole() {
      request({
        url: '/system/sysUserRole/addRole',
        method: 'post',
        data: {
          newRole: this.checkList,
          userId: this.roleForm.userId
        }
      }).then(res => {
        this.$message.success('分配成功')
        this.roleForm.role = false;
      })
    },
    postImgUploadSuccess(res, file) {
      if (res.code !== 200) {
        this.$message.error('上传失败: ' + res.message);
        return;
      }
      this.saveForm.props.postImgPath = res.data.url;
    },
    // 取消
    cancel(formName) {
      this.$refs[formName].clearValidate();
      this.$refs[formName].resetFields();
      this.saveForm.visible = false;
    }
  }
}
</script>

<style>
.role-checkbox .el-checkbox__label {
  display: none;
}
</style>
